package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.server.WebSocketServer;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.util.StringUtil;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Array;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 目标:
 *
 * @author YUE
 * @date 2024/6/24 10:38
 */
@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private WorkspaceService workspaceService;

    /*
       查询营业额
     */
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        // 已知开始 结束 日期 未知中间日期
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);

        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        List<Double> turnoverStatisticsList = new ArrayList<>();
        // 拿到每一天
        for (LocalDate date : dateList) {
            // 查询营业额
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            Map map = new HashMap();
            map.put("status", Orders.COMPLETED);
            map.put("begin", beginTime);
            map.put("end", endTime);

            Double turnover = orderMapper.getByMap(map);
            turnoverStatisticsList.add(turnover == null ? 0.0 : turnover);
        }

        TurnoverReportVO turnoverReportVO = new TurnoverReportVO();
        turnoverReportVO.setDateList(StringUtils.join(dateList, ","));
        turnoverReportVO.setTurnoverList(StringUtils.join(turnoverStatisticsList, ","));
        return turnoverReportVO;
    }


    /*
       用户统计
     */
    @Override
    public UserReportVO countUserByMap(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);

        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        List<Integer> countUsers = new ArrayList<>();
        List<Integer> newUsers = new ArrayList<>();
        // 查询用户总量 新增用户
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            Map map = new HashMap();
            map.put("endTime", endTime);

            Integer countUser = orderMapper.getUserByMap(map);
            countUsers.add(countUser);

            map.put("beginTime", beginTime);

            Integer newUser = orderMapper.getUserByMap(map);
            newUsers.add(newUser);
        }

        UserReportVO userReportVO = new UserReportVO();
        userReportVO.setDateList(StringUtils.join(dateList, ","));
        userReportVO.setNewUserList(StringUtils.join(newUsers, ","));
        userReportVO.setTotalUserList(StringUtils.join(countUsers, ","));
        return userReportVO;
    }

    /*
      订单统计
     */
    @Override
    public OrderReportVO getOrdersByMap(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);

        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        List<Integer> allOrdersList = new ArrayList<>();
        List<Integer> validOrdersList = new ArrayList<>();

        // 订单总数
        Integer countOrders = 0;

        Integer countvalidOrders = 0;

        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            Map map = new HashMap<>();
            map.put("begin", beginTime);
            map.put("end", endTime);
            // 每日订单数
            Integer allOrders = orderMapper.countByMap(map);
            allOrdersList.add(allOrders);
            countOrders += allOrders;

            // 每日有效订单数
            map.put("status", Orders.COMPLETED);
            Integer validOrders = orderMapper.countByMap(map);
            validOrdersList.add(validOrders);
            countvalidOrders += validOrders;
        }
        Double orderCompletionRate = 0.0;
        if (countOrders != 0) {
            orderCompletionRate = countvalidOrders.doubleValue() / countOrders;
        }

        OrderReportVO orderReportVO = OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(allOrdersList, ","))
                .validOrderCountList(StringUtils.join(validOrdersList, ","))
                .totalOrderCount(countOrders)
                .validOrderCount(countvalidOrders)
                .orderCompletionRate(orderCompletionRate)
                .build();
        return orderReportVO;
    }

    /*
      查询销量排名top10的接口
     */
    @Override
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {

        List<GoodsSalesDTO> salesDTOList = orderMapper.getSalesTop10();
        // 提取每个SalesDTO对象的name属性 流中的元素从SalesDTO对象变为String
        List<String> nameList = salesDTOList.stream().map(dto -> {
            return dto.getName();
        }).collect(Collectors.toList()); //  将流中的元素收集到新的List<String>中

        List<Integer> numberList = salesDTOList.stream().map(dto -> {
            return dto.getNumber();
        }).collect(Collectors.toList());


      SalesTop10ReportVO top10ReportVO = SalesTop10ReportVO.builder()
              .numberList(StringUtils.join(numberList,","))
              .nameList(StringUtils.join(nameList,","))
              .build();
        return top10ReportVO;
    }

    /*
       查看运营数据报表
     */
    @Override
    public void exportXlsx(HttpServletResponse response) throws IOException {
        LocalDate dateNow = LocalDate.now();
        LocalDate begin = dateNow.minusDays(30); //前30天
        LocalDate end = dateNow.minusDays(1);

        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        // 查询三十天内的运营数据
        BusinessDataVO businessData = workspaceService.getBusinessData(beginTime,endTime);
        // 使用输入流动读取到指定的模板文件
        InputStream input = getClass().getClassLoader().getResourceAsStream("POI/运营数据报表模板.xlsx");
        // 将查询到的数据读取到表中
        XSSFWorkbook excel = new XSSFWorkbook(input);

        // 获取Sheet
        XSSFSheet sheet = excel.getSheetAt(0);

        // 获取第二行 第二列
        sheet.getRow(1).getCell(1).setCellValue(begin.toString()+"至"+end.toString());
        // 营业额
        sheet.getRow(3).getCell(2).setCellValue(businessData.getTurnover());
        // 订单完成率
        sheet.getRow(3).getCell(4).setCellValue(businessData.getOrderCompletionRate());
        // 新增用户数
        sheet.getRow(3).getCell(6).setCellValue(businessData.getNewUsers());
        // 有效订单
        sheet.getRow(4).getCell(2).setCellValue(businessData.getValidOrderCount());
        // 平均单价
        sheet.getRow(4).getCell(4).setCellValue(businessData.getUnitPrice());

        // 明细数据
        for (int i = 0; i < 30; i++) { // 从第七行开始
            // 获取每一天
            LocalDate date = begin.plusDays(i);
            // 获取信息
             businessData = workspaceService.getBusinessData
             (LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
            XSSFRow row = sheet.getRow(7 + i);
            row.getCell(1).setCellValue(date.toString());

            // 营业额
            row.getCell(2).setCellValue(businessData.getTurnover());
            row.getCell(3).setCellValue(businessData.getValidOrderCount());
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            row.getCell(5).setCellValue(businessData.getUnitPrice());
            row.getCell(6).setCellValue(businessData.getNewUsers());
        }


        // 通过响应获取输出流 这个流对应的是客户端浏览器
        ServletOutputStream out = response.getOutputStream();
        excel.write(out);

        out.close();
        excel.close();


    }
}

